﻿using Com.Ctrip.Framework.Apollo;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Concurrent;
using System.IO;

namespace ApolloExtension.Core.Test
{
    public class ApolloConfig2
    {
        private static IConfiguration _configuration = null;
        private const string defaultNamespace = "application";
        private static ConcurrentDictionary<string, IConfiguration> _dic = new ConcurrentDictionary<string, IConfiguration>();

        public static IConfiguration Configuration
        {
            get
            {
                if (_configuration == null)
                    Init();
                return _configuration;
            }
        }

        static ApolloConfig2()
        {
            Init();
        }

        private static void Init()
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory() + "\\appsettings.json");
            if (!File.Exists(filePath))
            {
                throw new Exception("appsettings.json文件不存在，.Net Core下将读取此文件，请先配置");
            }

            _dic.GetOrAdd(defaultNamespace, key =>
            {
                var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                _configuration = new ConfigurationBuilder()
                   .AddApollo(builder.Build().GetSection("apollo"))
                  .AddDefault()
                  .AddNamespace(defaultNamespace)
                  .Build();
                _dic[defaultNamespace] = _configuration;
                return _configuration;
            });
        }
        public static IConfiguration GetIConfigurationByNamespace(string namespaceName)
        {
            return _dic.GetOrAdd(namespaceName, key =>
             {
                 var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                 _configuration = new ConfigurationBuilder()
                    .AddApollo(builder.Build().GetSection("apollo"))
                   .AddDefault()
                   .AddNamespace(namespaceName)
                   .Build();
                 _dic[defaultNamespace] = _configuration;
                 return _configuration;
             });
        }
    }
}
